package com.novel.app;


import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.graphics.Rect;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.dongdxiang.framework.http.ImageLoader;
import com.dongdxiang.framework.utils.SharedPreferenceUtils;
import com.novel.app.view.shucheng.bean.ShuChengEntity;
import com.novel.app.view.storys.bean.StoryEntity;

public class CommonUtils {
	/**
	 * 获取包名
	 * 
	 * @author kong
	 * @createDate 2014-4-21
	 * @param
	 * @return
	 */
	public static String getPackageName(Context c) {
		String str = "";
		PackageManager manager = c.getPackageManager();
		try {
			PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0);
			str = info.packageName; // 包名
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * 获得APP的版本名称
	 * 
	 * @param c
	 *            上下文
	 * @return 返回版本名称(例如: 3.2.1)
	 */
	public static String getAppVersionName(Context c) {
		try {
			PackageManager manager = c.getPackageManager();
			PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0);
			return info.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获得APP的版本编号
	 * 
	 * @param c
	 *            上下文
	 * @return 返回版本名称(例如: 3.2.1)
	 */
	public static int getAppVersionCode(Context c) {
		try {
			PackageManager manager = c.getPackageManager();
			PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0);
			return info.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return 0;
	}

	
	public final static String RESTART_ACTION = "com.restartapk.service";
	/**
	 * 杀死APP所有进程并延迟重启
	 */
	public static void restartAPP(Context context,long delayed){

		/**开启一个新的服务，用来重启本APP*/
		Intent intentService = new Intent();
		intentService.setAction(RESTART_ACTION);
		intentService.setPackage(context.getPackageName());
		intentService.putExtra("packageName",context.getPackageName());
		intentService.putExtra("delayed",delayed);
		context.startService(intentService);
		/**杀死整个进程**/
		 System.exit(0);
		//android.os.Process.killProcess(android.os.Process.myPid());
	}
	public static boolean isBackground(Context context) {

	    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
	    List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
	    for (RunningAppProcessInfo appProcess : appProcesses) {
	         if (appProcess.processName.equals(context.getPackageName())) {
	                if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
	                         // Log.i("后台", appProcess.processName);
	                          return true;
	                }else{
	                         // Log.i("前台", appProcess.processName);
	                          return false;
	                }
	           }
	    }
	    return false;
	}
	
	 // 校验Tag Alias 只能是数字,英文字母和中文
    public static boolean isValidTagAndAlias(String s) {
        Pattern p = Pattern.compile("^[\\u4E00-\\u9FA50-9a-zA-Z_@!#$&*+=.|￥¥]+$");
        Matcher m = p.matcher(s);
        return m.matches();
    }
	


	// 获取状态栏高度
	public static int getStatusHeight(Activity activity) {
		int statusHeight = 0;
		Rect localRect = new Rect();
		activity.getWindow().getDecorView()
				.getWindowVisibleDisplayFrame(localRect);
		statusHeight = localRect.top;
		if (0 == statusHeight) {
			Class<?> localClass;
			try {
				localClass = Class.forName("com.android.internal.R$dimen");
				Object localObject = localClass.newInstance();
				int i5 = Integer.parseInt(localClass
						.getField("status_bar_height").get(localObject)
						.toString());
				statusHeight = activity.getResources()
						.getDimensionPixelSize(i5);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return statusHeight;
	}

	public static String getMobile(Context context) {
		return (String) SharedPreferenceUtils.getInstance(context,
				Constants.APPINFO).get(Constants.MOBILE);
	}

	public static String getToken(Context context) {
		return (String) SharedPreferenceUtils.getInstance(context,
				Constants.APPINFO).get(Constants.USERTOKEN);
	}

	public static void setMobile(Context context, String mobile) {
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save(
				Constants.MOBILE, mobile);
	}

	public static void setToken(Context context, String token) {
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save(
				Constants.USERTOKEN, token);
	}


	public static void createView(Activity context,LinearLayout view, List<StoryEntity.NovelEntity> list,NovelClickListenter clickListenter){

		int img_h = context.getResources().getDimensionPixelSize(R.dimen.shucheng_img_h);
		int img_w = context.getResources().getDimensionPixelSize(R.dimen.shucheng_img_w);
		int window_w = context.getWindowManager().getDefaultDisplay().getWidth();
		int view_w =Math.round ((window_w - context.getResources().getDimensionPixelSize(R.dimen.magin)*2)/3);
		int index = 0;
		for(int i =0; i < 2 ; i ++){
			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
			LinearLayout linearLayout = new LinearLayout(context);
			layoutParams.setMargins(0,10,0,10);
			linearLayout.setOrientation(LinearLayout.HORIZONTAL);
			linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);

			linearLayout.setLayoutParams(layoutParams);
			for (int j = index; j < list.size(); j++){

				linearLayout.addView(createImg(context,list.get(j),view_w,img_w,img_h,clickListenter));
				index ++;
				if (index == 3) {
					break;
				}
			}
			view.addView(linearLayout);
		}
	}

	public static LinearLayout createImg(Context context ,final StoryEntity.NovelEntity shuCheng,int view_w,int img_w, int img_h , final NovelClickListenter clickListenter){
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(view_w,ViewGroup.LayoutParams.WRAP_CONTENT);
		LinearLayout linearLayout = new LinearLayout(context);
		linearLayout.setOrientation(LinearLayout.VERTICAL);
		layoutParams.gravity = Gravity.CENTER;
		layoutParams.weight = 1;
		linearLayout.setLayoutParams(layoutParams);

		ImageView imageView = new ImageView(context);
		LinearLayout.LayoutParams layoutParams_img = new LinearLayout.LayoutParams(img_w, img_h);
		imageView.setLayoutParams(layoutParams_img);
		imageView.setScaleType(ImageView.ScaleType.FIT_XY);
		imageView.setBackgroundColor(Color.parseColor("#F1F1F1"));
		ImageLoader.disImage(context,shuCheng.getImg_url(),imageView);

		LinearLayout.LayoutParams layoutParams_text = new LinearLayout.LayoutParams(img_w, ViewGroup.LayoutParams.WRAP_CONTENT);
		TextView textView = new TextView(context);
		textView.setLayoutParams(layoutParams_text);
		textView.setText(shuCheng.getName());
		textView.setLines(1);
		textView.setEllipsize(TextUtils.TruncateAt.END);

		linearLayout.addView(imageView);
		linearLayout.addView(textView);
		linearLayout.setClickable(true);
		linearLayout.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				clickListenter.goToNovel(shuCheng.getId());
			}
		});
		return linearLayout;
	}

	public interface NovelClickListenter{
		public void goToNovel(String id);
	}
}
